<template>
	<view class="login">
		<!-- 页面头部 -->
		<view class="header">
			<image class="logo" src="../../static/logo.png" mode="aspectFit"></image>
			<view class="title">EccentricPet</view>
			<view class="subtitle">让宠物生活更精彩</view>
		</view>

		<!-- 登录表单 -->
		<view class="form">
			<!-- 手机号输入 -->
			<view class="input-group">
				<uni-icons type="phone" size="20" color="#999"></uni-icons>
				<input type="number" maxlength="11" placeholder="请输入手机号" v-model="phone" />
			</view>

			<!-- 验证码输入 -->
			<view class="input-group">
				<uni-icons type="locked" size="20" color="#999"></uni-icons>
				<input type="number" maxlength="6" placeholder="请输入验证码" v-model="code" />
				<view class="code-btn" :class="{ disabled: counting }" @tap="sendCode">
					{{ counting ? `${count}s后重试` : '获取验证码' }}
				</view>
			</view>

			<!-- 登录按钮 -->
			<button class="submit-btn" @tap="handleLogin">登录</button>

			<!-- 分割线 -->
			<view class="divider">
				<text>或使用以下方式</text>
			</view>

			<!-- 微信登录 -->
			<button class="wechat-btn" @tap="handleWechatLogin">
				<uni-icons type="weixin" size="24" color="#fff"></uni-icons>
				<text>微信一键登录</text>
			</button>

			<!-- 账号密码登录 -->
			<view class="input-group">
				<uni-icons type="person" size="20" color="#999"></uni-icons>
				<input type="text" placeholder="请输入账号" v-model="formData.username" />
			</view>
			<view class="input-group">
				<uni-icons type="locked" size="20" color="#999"></uni-icons>
				<input type="password" placeholder="请输入密码" v-model="formData.password" />
			</view>
			<button class="submit-btn" @tap="loginByUsername">账号密码登录</button>
		</view>

		<!-- 用户协议 -->
		<view class="agreement">
			<checkbox :checked="isAgree" @tap="isAgree = !isAgree" />
			<text>已阅读并同意</text>
			<text class="link" @tap="showAgreement">《用户协议》</text>
			<text>和</text>
			<text class="link" @tap="showPrivacy">《隐私政策》</text>
		</view>

		<!-- 添加注册入口 -->
		<view class="register-box">
			<text>还没有账号？</text>
			<text class="register-link" @click="toRegister">立即注册</text>
		</view>
	</view>
</template>

<script>
	import { fetchAndCacheFollowFansCount } from '@/utils/followCache'

	export default {
		data() {
			return {
				phone: '', // 手机号
				code: '', // 验证码
				counting: false, // 是否在倒计时
				count: 60, // 倒计时秒数
				isAgree: false, // 是否同意协议
				loading: false, // 加载状态
				appid: 'wxfa575231aabe0e47', // 替换为您的微信小程序AppID
				secret: '8bd4fb3fd689e26f4b9e22a0792a74e0', // 替换为您的微信小程序AppSecret
				formData: {
					username: '',
					password: ''
				}
			}
		},
		methods: {
			// 发送验证码
			async sendCode() {
				if (this.counting) return

				// 验证手机号
				if (!/^1[3-9]\d{9}$/.test(this.phone)) {
					uni.showToast({
						title: '请输入正确的手机号',
						icon: 'none'
					})
					return
				}

				try {
					const uniIdCo = uniCloud.importObject('uni-id-co')
					const res = await uniIdCo.sendSmsCode({
						mobile: this.phone,
						type: 'login'
					})

					if (res.code === 0) {
						// 开始倒计时
						this.counting = true
						this.count = 60

						const timer = setInterval(() => {
							this.count--
							if (this.count <= 0) {
								this.counting = false
								clearInterval(timer)
							}
						}, 1000)

						uni.showToast({
							title: '验证码已发送',
							icon: 'success'
						})
					} else {
						uni.showToast({
							title: res.message || '发送失败',
							icon: 'none'
						})
					}
				} catch (error) {
					console.error('发送验证码错误:', error)
					uni.showToast({
						title: '发送失败，请重试',
						icon: 'none'
					})
				}
			},

			// 手机号登录
			async handleLogin() {
				if (!this.isAgree) {
					uni.showToast({
						title: '请先同意用户协议',
						icon: 'none'
					})
					return
				}

				// 验证手机号
				if (!/^1[3-9]\d{9}$/.test(this.phone)) {
					uni.showToast({
						title: '请输入正确的手机号',
						icon: 'none'
					})
					return
				}

				// 验证验证码
				if (!/^\d{6}$/.test(this.code)) {
					uni.showToast({
						title: '请输入正确的验证码',
						icon: 'none'
					})
					return
				}

				try {
					this.loading = true

					// 使用 uni-id-co 云对象
					const uniIdCo = uniCloud.importObject('uni-id-co')
					const res = await uniIdCo.loginBySms({
						mobile: this.phone,
						code: this.code
					})

					if (res.code === 0) { // uni-id-co 返回 code 为 0 表示成功
						// 保存 token
						uni.setStorageSync('uni_id_token', res.newToken.token)
						uni.setStorageSync('uni_id_token_expired', res.newToken.tokenExpired)

						// 获取用户信息
						const userInfo = await uniIdCo.getUserInfo()
						if (userInfo.code === 0) {
							// 存储用户信息
							uni.setStorageSync('userInfo', userInfo.data)
							await fetchAndCacheFollowFansCount(userInfo.data.userId)
						}
						uni.showToast({
							title: '登录成功',
							icon: 'success'
						})

						setTimeout(() => {
							uni.navigateBack()
						}, 1500)
					} else {
						uni.showToast({
							title: res.message || '登录失败',
							icon: 'none'
						})
					}
				} catch (error) {
					console.error('登录错误:', error)
					uni.showToast({
						title: '登录失败，请重试',
						icon: 'none'
					})
				} finally {
					this.loading = false
				}
			},

			// 微信一键登录
			async handleWechatLogin() {
				if (!this.isAgree) {
					uni.showToast({
						title: '请先同意用户协议',
						icon: 'none'
					})
					return
				}

				try {
					this.loading = true

					// 获取用户信息
					const userProfile = await new Promise((resolve, reject) => {
						uni.getUserProfile({
							desc: '用于完善用户资料',
							success: (res) => resolve(res),
							fail: (err) => reject(err)
						})
					})

					// 获取登录code
					const loginResult = await new Promise((resolve, reject) => {
						uni.login({
							provider: 'weixin',
							success: (res) => resolve(res),
							fail: (err) => reject(err)
						})
					})

					if (!loginResult.code) {
						throw new Error('获取微信登录凭证失败')
					}

					const uniIdCo = uniCloud.importObject('uni-id-co')
					const res = await uniIdCo.loginByWeixin({
						code: loginResult.code,
					})

					if (res.errCode === 0) {
						uni.setStorageSync('uni_id_token', res.newToken.token)
						uni.setStorageSync('uni_id_token_expired', res.newToken.tokenExpired)
						
						// 获取数据库中的用户信息
						const user = uniCloud.importObject('user')
						const dbUserInfo = await user.getUserInfo({
							userId: res.uid
						})
						
						let finalUserInfo = {}
						
						if (dbUserInfo.code === 200) {
							// 如果数据库中已有nickname和avatar，优先使用数据库中的
							if (dbUserInfo.data.nickname && dbUserInfo.data.avatar) {
								finalUserInfo = {
									userId: res.uid,
									nickname: dbUserInfo.data.nickname,
									avatar: dbUserInfo.data.avatar
								}
							} else {
								// 数据库中没有，使用微信的信息并更新到数据库
								finalUserInfo = {
									userId: res.uid,
									nickname: userProfile.userInfo.nickName,
									avatar: userProfile.userInfo.avatarUrl
								}
								// 更新用户信息到数据库
								await user.updateUserInfo({
									userId: res.uid,
									nickname: finalUserInfo.nickname,
									avatar: finalUserInfo.avatar
								})
							}
							// 获取并缓存关注和粉丝数量
							await fetchAndCacheFollowFansCount(res.uid)
						}

						// 保存用户信息到本地
						uni.setStorageSync('userInfo', finalUserInfo)
						uni.showToast({
							title: '登录成功',
							icon: 'success'
						})

						setTimeout(() => {
							uni.navigateBack()
						}, 1500)
					} else {
						uni.showToast({
							title: res.message || '登录失败',
							icon: 'none'
						})
					}
				} catch (error) {
					console.error('微信登录失败:', error)
					uni.showToast({
						title: error.message || '微信登录失败，请稍后重试',
						icon: 'none'
					})
				} finally {
					this.loading = false
				}
			},

			// 显示用户协议
			showAgreement() {
				uni.navigateTo({
					url: '/pages/agreement/agreement'
				})
			},

			// 显示隐私政策
			showPrivacy() {
				uni.navigateTo({
					url: '/pages/privacy/privacy'
				})
			},

			// 跳转到手机号注册页面
			toRegister() {
				uni.navigateTo({
					url: '/pages/register/register-by-psd'
				})
			},

			async loginByUsername() {
				if (!this.isAgree) {
					uni.showToast({
						title: '请先同意用户协议',
						icon: 'none'
					})
					return
				}
				if (!this.formData.username) {
					return uni.showToast({ title: '请输入用户名', icon: 'none' })
				}
				if (!this.formData.password) {
					return uni.showToast({ title: '请输入密码', icon: 'none' })
				}
				try {
					const uniIdCo = uniCloud.importObject('uni-id-co')
					const res = await uniIdCo.login({
						username: this.formData.username,
						password: this.formData.password
					})
					if (res.errCode === 0) {
						uni.setStorageSync('uni_id_token', res.newToken.token)
						uni.setStorageSync('uni_id_token_expired', res.newToken.tokenExpired)

						// 获取数据库中的用户信息
						const user = uniCloud.importObject('user')
						const dbUserInfo = await user.getUserInfo({
							userId: res.uid
						})

						let finalUserInfo = {
									userId: res.uid,
									nickname: dbUserInfo.data.nickname,
									avatar: dbUserInfo.data.avatar
								}
						uni.setStorageSync('userInfo', finalUserInfo)
						await fetchAndCacheFollowFansCount(res.uid)
						uni.showToast({ title: '登录成功', icon: 'success' })
						uni.reLaunch({ url: '/pages/my/my' })
					} else {
						uni.showToast({ title: res.errMsg || '登录失败', icon: 'none' })
					}
				} catch (e) {
					uni.showToast({ title: e.errMsg || '登录失败', icon: 'none' })
				}
			}
		}
	}
</script>

<style lang="scss">
	.login {
		min-height: 100vh;
		padding: 40rpx;
		background-color: #fff;
		display: flex;
		flex-direction: column;

		.header {
			display: flex;
			flex-direction: column;
			align-items: center;
			margin-bottom: 60rpx;

			.logo {
				width: 160rpx;
				height: 160rpx;
				margin-bottom: 20rpx;
			}

			.title {
				font-size: 40rpx;
				font-weight: bold;
				color: #333;
				margin-bottom: 10rpx;
			}

			.subtitle {
				font-size: 28rpx;
				color: #999;
			}
		}

		.form {
			.input-group {
				display: flex;
				align-items: center;
				height: 100rpx;
				padding: 0 30rpx;
				margin-bottom: 30rpx;
				background-color: #f8f8f8;
				border-radius: 50rpx;

				input {
					flex: 1;
					margin-left: 20rpx;
					font-size: 28rpx;
				}

				.code-btn {
					padding: 10rpx 30rpx;
					font-size: 28rpx;
					color: #5cb85c;

					&.disabled {
						color: #999;
					}
				}
			}

			.submit-btn {
				width: 100%;
				height: 100rpx;
				line-height: 100rpx;
				text-align: center;
				background-color: #5cb85c;
				color: #fff;
				font-size: 32rpx;
				border-radius: 50rpx;
				margin-top: 40rpx;
			}

			.divider {
				display: flex;
				align-items: center;
				justify-content: center;
				margin: 40rpx 0;

				&::before,
				&::after {
					content: '';
					flex: 1;
					height: 1rpx;
					background-color: #eee;
				}

				text {
					padding: 0 20rpx;
					font-size: 24rpx;
					color: #999;
				}
			}

			.wechat-btn {
				display: flex;
				align-items: center;
				justify-content: center;
				width: 100%;
				height: 100rpx;
				background-color: #07c160;
				color: #fff;
				font-size: 32rpx;
				border-radius: 50rpx;
				margin-bottom: 10rpx;

				text {
					margin-left: 10rpx;
				}
			}
		}

		.agreement {
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 24rpx;
			color: #999;
			padding: 20rpx 0;

			checkbox {
				margin-right: 10rpx;
			}

			.link {
				color: #5cb85c;
			}
		}

		.register-box {
			margin-top: 30rpx;
			text-align: center;
			font-size: 28rpx;
			
			.register-link {
				color: #007AFF;
				margin-left: 10rpx;
			}
		}
	}
</style>